
import UIKit

struct PopUpViewConfig {
    private (set) var view: UIView!
    private (set) var size: CGSize!
    init(view: UIView, size: CGSize) {
        view.tag = 50501
        self.view = view
        self.size = size
    }
}

class Pop_Up_Custom_View: UIView {
    
    /// 点击空白区是否域移除视图，默认为true
    var isCloseFromClean: Bool = true
    
    private (set) var config: PopUpViewConfig?
    
    init(config: PopUpViewConfig,isBottom:Bool = false) {
        super.init(frame: .zero)
        tag = 50502
        self.config = config
        backgroundColor = .blackComponent(0)
        addSubview(config.view)
        config.view.snp.makeConstraints { make in
            if isBottom == true{
                make.left.bottom.equalTo(0)
            }else{
                make.center.equalToSuperview()
            }
            make.size.equalTo(CGSize(width: config.size.width, height: config.size.height))
        }
//        NotificationCenter.default.addObserver(forName: TDNotificationName.receivedAnchorCallingNotification, object: nil, queue: nil) {[weak self] notification in
//            self?.animatedDismiss()
//        }
    }
    
    init(config: PopUpViewConfig,top:CGFloat,right:CGFloat) {
        super.init(frame: .zero)
        tag = 50502
        self.config = config
        backgroundColor = .blackComponent(0)
        addSubview(config.view)
        config.view.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: config.size.width, height: config.size.height))
            make.top.equalTo(top)
            make.right.equalTo(-right)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        assert(config != nil, "请使用init(config: PopUpViewConfig)方法初始化")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isCloseFromClean {
            layoutIfNeeded()
            let touch = touches.first
            guard let point = touch?.location(in: self), let view = config?.view, !view.frame.contains(point) else { return }
            downAnimatedDismiss()
        }
    }
}


extension UIView {
    
    /// 渐变色枚举
    enum GradientColor: Equatable {
        
        case themeButton
        
        case topToBottom(colors: [UIColor])
        
        case leftToRight(colors: [UIColor])
        
        static func == (lhs: UIView.GradientColor, rhs: UIView.GradientColor) -> Bool {
            return true
        }
        
    }
    
    func removeGradient() {
        if let layers = layer.sublayers {
            for item in layers {
                if item is CAGradientLayer {
                    item.removeFromSuperlayer()
                }
            }
        }
    }
    
    /// 设置渐变色
    /// - Parameter color: 颜色枚举
    func setGrandient(color: GradientColor) {
        clipsToBounds = true
        superview?.layoutIfNeeded()
        let layer = CAGradientLayer()
        layer.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
        if case .topToBottom(_) = color {
            layer.locations = [0,1]
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 0, y: 1)
        }else if case .themeButton = color {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }else {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }
        self.layer.insertSublayer(layer, at: 0)
    }
    
    /// 按照rect设置渐变色
    /// - Parameters:
    ///   - color: 颜色
    ///   - bounds: rect
    func setGrandient(color: GradientColor, bounds: CGRect) {
        self.clipsToBounds = true
        let layer = CAGradientLayer()
        layer.frame = bounds
        if case .topToBottom(_) = color {
            layer.locations = [0,1]
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 0, y: 1)
        }else if case .themeButton = color {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }else {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }
        self.layer.insertSublayer(layer, at: 0)
    }
    
    /// 当有新弹窗准备弹出时，关闭之前已经弹出的框
    static func dismissBeforePopupView() {
        UIApplication.shared.keyWindow?.subviews.forEach {
            if $0.tag == 50502 {
                $0.animatedDismiss()
            }
        }
    }
    
    func noAnimatedPop() {
        if let view = UIApplication.shared.keyWindow {
            view.addSubview(self)
            self.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            var centerView: UIView?
            for v in self.subviews {
                if v.tag == 50501 {
                    centerView = v
                }
            }
        }
    }
    /// 弹窗动画
    func animatedPop() {
        if let view = UIApplication.shared.keyWindow {
            view.addSubview(self)
            self.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            var centerView: UIView?
            for v in self.subviews {
                if v.tag == 50501 {
                    centerView = v
                }
            }
            guard centerView != nil else { return }
            centerView?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
            UIView.animate(withDuration: 0.35, delay: 0.0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(7<<16)), animations: {
                centerView?.transform = .identity
                self.backgroundColor = .blackComponent(0.6)
            }, completion: { isFinish in
                
            })
        }
    }
    
    /// 上移动画
    func upAnimatedPop() {
        if let view = UIApplication.shared.keyWindow {
            var centerView: UIView?
            for v in self.subviews {
                if v.tag == 50501 {
                    centerView = v
                }
            }
            guard centerView != nil else { return }
            
            UIView.animate(withDuration: 0.35, delay: 0.0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(7<<16)), animations: {
                
                view.addSubview(self)
                self.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                self.backgroundColor = .blackComponent(0.6)
                
            }, completion: { isFinish in
                
            })
        }
    }

    
    static var popUpViewDismissClosure: (()->Void)?
    
    func noAnimatedDismiss() {
        self.removeFromSuperview()
    }
    /// 移除弹窗动画（需要跟弹窗动画配合使用）
    func animatedDismiss() {
        var centerView: UIView?
        for v in self.subviews {
            if v.tag == 50501 {
                centerView = v
            }
        }
        UIView.animate(withDuration: 0.3) {
            self.backgroundColor = .blackComponent(0)
            centerView?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
        } completion: { isFinish in
            self.removeFromSuperview()
            if let closure = UIView.popUpViewDismissClosure {
                closure()
            }
        }
    }
    
    func downAnimatedDismiss() {
        var centerView: UIView?
        for v in self.subviews {
            if v.tag == 50501 {
                centerView = v
            }
        }
        UIView.animate(withDuration: 0.3) {
            self.backgroundColor = .blackComponent(0)
            centerView?.alpha = 0
        } completion: { isFinish in
            self.removeFromSuperview()
            if let closure = UIView.popUpViewDismissClosure {
                closure()
            }
        }
    }

}
